package com.chuangke.common.data.filter;

import com.chuangke.common.constant.Config;

import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Function;

public class ListDataFilter<T> {
	
	private List<T> sourceDatalist ;
	private FilterResult<T> filterResult ;

	public static <T>ListDataFilter<T> of(List<T> list) {
		ListDataFilter<T> bisFilter = new ListDataFilter<>() ;
		bisFilter.filterResult = new FilterResult<>() ;
		bisFilter.sourceDatalist = list ;
		return bisFilter ;
	}
	
	public ListDataFilter<T> filter(BiConsumer<List<T>, FilterResult<T>> consumer) {
		if (sourceDatalist == null || sourceDatalist.isEmpty()) {
			return this ;
		}
		
		consumer.accept(sourceDatalist, filterResult);
		
		return this ;
	}
	
	public ListDataFilter<T> cause(Function<T, String> function){
		filterResult.getCause().append(getFilterMsg(filterResult, function));
		return this ;
	}
	
	private  String getFilterMsg(FilterResult<T> filter, Function<T, String> function) {
		StringBuilder msg = new StringBuilder();
		int msgSize = Math.min(filter.getCannotList().size(), Config.MSG_LAST_SIZE);
		for (int i = 0; i < msgSize; i++) {
			msg.append(function.apply(filter.getCannotList().get(i)));
			msg.append("<br/>");
		}

		if (filter.getCannotList().size() > msgSize) {
			msg.append("............");
			msg.append("<br/>");
		}

		return msg.toString();
	}

	public FilterResult<T> getFilter() {
		return filterResult;
	}
	
}
